import React from 'react';
import { Spin, Button, Modal, Checkbox, message } from 'antd';
import { isEqual, isEmpty } from 'lodash';
import {WeaTools, WeaErrorPage, WeaInput, WeaSelect, WeaFormItem, WeaLocaleProvider} from 'ecCom';
const getLabel = WeaLocaleProvider.getLabel;
const { ls } = WeaTools;
import EHeader from '../common/EHeader';
import FooterMore from "../common/FooterMore";
import { NoRightCom } from '../../util/common';
import {getLSValue, initLSValue, getDefaultPathname, setLSValue} from './LoginUtil';
import E9QRCode from './E9QRCode';
import objectAssign from 'object-assign';
import './style.css';
//元素组件
class Login extends React.Component {
    constructor(props) {
        super(props);
        this.state = objectAssign({}, {
                edata: null,
                win_width: jQuery(window).width(),
                win_height: jQuery(window).height(),
                isLogging: false,
                hasMultiLang: false,
                multiLangVisible: false,
                loginFormHiddenItems: [],
                loginSetting: {},
                validateCode: '/weaver/weaver.file.MakeValidateCode',
                queryParams: {logintype: '1'},
                loginFormItems: [],
                multiLangs: [],
                refresh: false,
                qrCode: {}
            }, objectAssign({}, getLSValue('portal_login', 'loginCache'), {
                loginType: getLSValue('portal_login', 'loginType') || 'form',
                langId: getLSValue('portal_login', 'langId') || WeaTools.ls.getJSONObj('languageidweaver') || '7',
                langText: getLSValue('portal_login', 'langText') || '简体中文',
                isRememberAccount: getLSValue('portal_login', 'isRememberAccount') || false,
                isRememberPassword: getLSValue('portal_login', 'isRememberPassword') || false,
                cacheAccount: getLSValue('portal_login', 'cacheAccount') || '',
                cachePassword: getLSValue('portal_login', 'cachePassword') || '',
                initialSlide: getLSValue('portal_login', 'initialSlide') || 0,
                autoCarousel: getLSValue('portal_login', 'autoCarousel') || false,
                carouselTime: getLSValue('portal_login', 'carouselTime') || 3,
        }));
        this.handleDelete = this.handleDelete.bind(this);
        this.handleRefresh = this.handleRefresh.bind(this);
        this.onPasswordForget = this.onPasswordForget.bind(this);
        this.onRememberChange = this.onRememberChange.bind(this);
        this.onValidateCodeChange = this.onValidateCodeChange.bind(this);
        this.getLoginForm = this.getLoginForm.bind(this);
        this.onQCLogin = this.onQCLogin.bind(this);
        this.getMultiLangs = this.getMultiLangs.bind(this);
        this.onLogin = this.onLogin.bind(this);
    }

    componentDidMount() {
        const {cacheAccount:loginId, langId} = this.state;
        WeaLocaleProvider.getLocaleLabelByLang(['common', 'portal'], langId).then(()=>{
            this.getLoginForm({loginId, langId});
        });
        this.getMultiLangs();
    }

    handleDelete(){
        this.setState({
            edata: null,
        });
        ls.set('edata-'+this.props.config.params.eid, null);
    }

    handleRefresh(){
        this.setState({
            refresh: true,
        });
        this.getLoginForm();
    }

    getLoginForm(params = {}) {
        this.setState({
            edata: ls.getJSONObj('edata-'+this.props.config.params.eid),
        });
        const { queryParams, langId: langid } = this.state;
        const {logintype = '1'} = queryParams;
        const { loginId = '', langId = langid } = params;
        window.doLoginAction && window.doLoginAction('getLoginForm', {
            queryParams: queryParams,
            logintype: logintype,
            loginid: loginId,
            langid: langId,
            callback: (result) => {
                const { hasMultiLang = false, loginFormItems = [], loginSetting = {}, qrCode={} } = result;
                ls.set('edata-'+this.props.config.params.eid, result);
                this.setState({hasMultiLang, loginFormItems, loginSetting, qrCode, edata: result});
            }
        });
    }

    onPasswordForget(params = {}) {
        const {langId = this.state.langId} = params;
        window.doLoginAction && window.doLoginAction('forgetPassword', {langid: langId});
    };

    onRememberChange(type, checked) {
        const {isRememberAccount, isRememberPassword} = this.state;
        if ('account' == type) {
            this.setState({
                isRememberAccount: checked,
                isRememberPassword: !checked ? checked : isRememberPassword
            });
        } else if ('password' == type) {
            this.setState({
                isRememberAccount: checked ? checked : isRememberAccount,
                isRememberPassword: checked
            });
        }
    }

    onValidateCodeChange() {
        setTimeout(() => this.setState({validateCode: `/weaver/weaver.file.MakeValidateCode?seriesnum_=${++this.seriesnum_}`}), 50);
    }

    onQCLogin() {
        const {langId, langText, qrCode} = this.state;
        WeaTools.callApi('/mobile/plugin/login/QCLoginStatus.jsp', 'POST', {
            langid: langId,
            loginkey: qrCode.loginkey,
            isie: !!WeaTools.ua.browser === "IE"
        }, 'text').then((result) => {
            if (jQuery.trim(result) != '0' && jQuery.trim(result) != '9' && jQuery.trim(result) != '-99') {
                jQuery.setSessionTimeZone && jQuery.setSessionTimeZone();

                setLSValue('portal_login', 'langId', langId);
                setLSValue('portal_login', 'langText', langText);
                WeaTools.ls.set('languageidweaver', langId);

                window.open('/wui/index.html?#/main', '_blank');
            }
        });
    }

    // getMultiLangs(params = {}) {
    //     WeaTools.callApi('/api/system/language/base/getActiveLanguage', 'GET', params).then((result) => {
    //         if (result.status == '1') {
    //             const {activeLanguageInfo, activeLanguageIds, languageIdentify} = result;
    //             this.multiLangs = activeLanguageInfo;
    //         }
    //     });
    // }

    getMultiLangs(params = {}) {
        WeaTools.callApi('/api/system/language/base/getActiveLanguage', 'GET', params).then((result) => {
            if (result.status == '1') {
                const {activeLanguageInfo, activeLanguageIds, languageIdentify} = result;
                this.setState({
                    multiLangs: activeLanguageInfo
                });
                setLSValue('portal_login', 'multiLangs', activeLanguageInfo);
                WeaTools.ls.set('activeLanguageIds', activeLanguageIds);
                WeaTools.ls.set('languageIdentify', languageIdentify);
            }
        });
    }

    onLogin() {
        const {queryParams, langId, langText, isRememberAccount, isRememberPassword, loginSetting} = this.state;
        const {logintype = '1'} = queryParams;
        this.setState({isLogging: true});
        window.doLoginAction && window.doLoginAction('login', {
            queryParams: queryParams,
            logintype: logintype,
            langid: langId,
            loginSetting: loginSetting,
            success: (username, password) => {
                jQuery.setSessionTimeZone && jQuery.setSessionTimeZone();

                let cacheAccount = '';
                let cachePassword = '';
                if (isRememberAccount) cacheAccount = username;
                if (isRememberPassword) cachePassword = password;
                this.setState({isRememberAccount, isRememberPassword, cacheAccount, cachePassword});

                setLSValue('portal_login', 'langId', langId);
                setLSValue('portal_login', 'langText', langText);
                setLSValue('portal_login', 'cacheAccount', cacheAccount);
                setLSValue('portal_login', 'cachePassword', cachePassword);
                setLSValue('portal_login', 'isRememberAccount', isRememberAccount);
                setLSValue('portal_login', 'isRememberPassword', isRememberPassword);

                initLSValue(username, langId);
                WeaTools.ls.set('languageidweaver', langId);

                if (logintype == '2') {
                    window.location.href = '/spa/crmPortal/mobx/index.html#/main';
                } else {
                    // 判断当前登录日期和上次登录的日期是否为同一天，不是同一天则刷新页面
                    const date = new Date();
                    const logindate = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate();
                    const _logindate = WeaTools.ls.getStr('logindate');

                    if (logindate != _logindate) {
                        WeaTools.ls.set('logindate', logindate);
                    }
                    window.open('/wui/index.html?#/main', '_blank');
                }
                this.setState({isLogging: false});
            },
            failure: (params = {}) => {
                if (params.reflashValidateCode) {
                    this.onValidateCodeChange();
                }
                this.getLoginForm();
                this.setState({isLogging: false});
            }
        });
    }

    render() {
        const {
            isLogging,
            isRememberPW,
            isRememberAccount,
            isRememberPassword,
            cacheAccount,
            cachePassword,
            langId,
            loginSettingInfo = {},
            loginFormHiddenItems,
            loginSetting = {},
            validateCode,
            loginType,
            loginFormItems = [],
            hasMultiLang,
            multiLangs,
            loginId,
            edata
        } = this.state;
        const { config, fontSizeMp } = this.props;
        if(!config) return <div/>;
        const { item, isHasRight } = config;
        const { eid, ebaseid, contentview, style } = item;
        const { style: style1= {} } = contentview;
        const {loginForm = {}} = loginSettingInfo;
        const {color, backgroundColor} = loginForm;
        const {needforgotpassword} = loginSetting;
        if(!config) return <div/>;
        let EmultiLang = '';
        if(isHasRight){
            if(isEmpty(edata)) return <div/>;
        }else{
            return <NoRightCom ecId={`${this && this.props && this.props.ecId || ''}_NoRightCom@iiel7h`}/>;
        }
        if (!hasMultiLang) {
            EmultiLang= (<div className="login-multiLang"></div>);
        }else{
            let langlId=langId+"";
            EmultiLang = (
                <div className="login-multiLang" style={{display: 'inline-block'}}>
                    <div style={{display: 'inline-block'}}>
                        <WeaSelect ecId={`${this && this.props && this.props.ecId || ''}_WeaSelect@aqqzsw`}
                            value={langlId}
                            style={{marginLeft:'10px', border: 'none' ,width: '82px' }}
                            options={multiLangs.map((item) => {
                                return { key: item.id, showname: item.language }
                            })}
                            onChange={(value, showname)=>{

                                WeaLocaleProvider.getLocaleLabelByLang(['common', 'portal'], value).then(()=>{
                                    this.setState({langId: value, langText: showname});
                                    this.getLoginForm({langId: value});
                                });
                            }}
                        />
                    </div>
                    <div className='login-toggle login-draggable-display portal-login-element' >
                        {loginType == 'form' ? <i className="icon-coms-Scan" style={{color: '#BFBFBF'}} onClick={()=>this.setState({loginType: 'QRCode'})}/> : <i className="icon-coms-Revoke2" style={{color: '#BFBFBF'}} onClick={()=>this.setState({loginType: 'form'})}/>}
                    </div>
                </div>
            );
        }
        let verificationCode = <div/>
        loginFormItems.map((item, index) => {
            if (item.atype == 'validatecode') {
                verificationCode = (
                    <div key={index} className="login-form-item" style={{color, borderBottom: 'none', display: 'inline-block'}}>
                        <WeaInput ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@5o0wgd@${item.id}`}
                            type={item.type}
                            name={item.name}
                            id={item.id}
                            style={{width: '128px', display: 'inline-block', position: 'relative'}}
                            placeholder={item.label}
                        />
                        <div style={{width: '112px', height: '38px', display: 'inline-block', marginLeft: '20px', position: 'absolute', top: '-4px'}}>
                            <img src={validateCode} alt="" onClick={this.onValidateCodeChange}/>
                        </div>
                    </div>
                );
            }
        })
        return <div className="item"
                    style={style}
                    id={`item_${eid}`}
                    data-eid={eid} data-ebaseid={ebaseid}
                    data-needRefresh={item.needRefresh}
                    data-cornerTop={item.cornerTop}
                    data-cornerTopRadian={item.cornerTopRadian}
                    data-cornerBottom={item.cornerBottom}
                    data-cornerBottomRadian={item.cornerBottomRadian}>
                    <EHeader ecId={`${this && this.props && this.props.ecId || ''}_EHeader@qw5y66`} config={config} handleRefresh={this.handleRefresh} handleDelete={this.handleDelete} fontSizeMp={fontSizeMp}/>

                    <div className='login-form-box login-draggable-display portal-login-element'>
                        {EmultiLang}
                        {loginType == 'form' ?
                            <div className="login-form">
                                {
                                    loginFormItems.map((item, index) => {
                                        let defaultValue = '';
                                        if (item.atype == 'account') {
                                            defaultValue = cacheAccount;
                                        } else if (item.atype == 'password') {
                                            defaultValue = cachePassword;
                                        }

                                        let itemComp = (
                                            <div key={index} className="login-form-item" style={{color}}>
                                                <span className={'login-form-label'} onClick={this.onLabelClick}>{item.label}:</span>
                                                <WeaInput ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@nrwg2q@${item.id}`}
                                                    type={item.type}
                                                    name={item.name}
                                                    id={item.id}
                                                    className="login-form-input"
                                                    defaultValue={defaultValue}
                                                />
                                            </div>
                                        );

                                        if (item.atype == 'validatecode') {
                                            itemComp = (<div></div>);
                                        }

                                        return itemComp;
                                    })
                                }
                                {
                                    loginFormHiddenItems.map((item, index) => {
                                        return <div key={index} style={{display: 'none'}} dangerouslySetInnerHTML={{__html: item.html}}></div>;
                                    })
                                }
                                <div className="login-form-remember" style={{color}}>
                                    {
                                        needforgotpassword == '1' && (
                                            <div className="login-form-remember-forget" title={getLabel(81614, '忘记密码')}>
                                                <span onClick={() => this.onPasswordForget()}>{getLabel(81614, '忘记密码')}</span>
                                            </div>
                                        )
                                    }
                                    <div className={'login-form-remember-content'}>
                                        <div className={`login-form-remember-account`} title={getLabel(381949, '记住账号')}>
                                            <Checkbox ecId={`${this && this.props && this.props.ecId || ''}_Checkbox@9wf9md`} checked={isRememberAccount} onChange={(e) => this.onRememberChange('account', e.target.checked)}>{getLabel(381949, '记住账号')}</Checkbox>
                                        </div>
                                        <div className={`login-form-remember-password`} title={getLabel(25722, '记住密码')}>
                                            <Checkbox ecId={`${this && this.props && this.props.ecId || ''}_Checkbox@vcn7fd`} checked={isRememberPassword} onChange={(e) => this.onRememberChange('password', e.target.checked)}>{getLabel(25722, '记住密码')}</Checkbox>
                                        </div>
                                    </div>
                                    <div className="login-form-clear"></div>
                                </div>
                                {verificationCode}
                                <div className="login-form-submit" style={{paddingLeft: '71px', marginTop: '32px'}}>
                                    <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@r6ev8x`} loading={isLogging} className="login-form-submit-btn" onClick={this.onLogin}>
                                        {getLabel(388151, '登陆')}
                                    </Button>
                                </div>
                            </div>
                         : <E9QRCode ecId={`${this && this.props && this.props.ecId || ''}_E9QRCode@03gk8h`} datas={this.state} getLoginForm={this.getLoginForm} onQCLogin={this.onQCLogin}/> }
                        <div style = {{textAlign:'right'}} id={`footer_${eid}`}><FooterMore ecId={`${this && this.props && this.props.ecId || ''}_FooterMore@hc4j93`} config={this.props.config}/></div>
                    </div>
            </div>;
    }
}

class MyErrorHandler extends React.Component {
    render() {
        const hasErrorMsg = this.props.error && this.props.error !== "";
            return ( <WeaErrorPage ecId={`${this && this.props && this.props.ecId || ''}_WeaErrorPage@e41gu2`} msg = { hasErrorMsg ? this.props.error : getLabel(388017,"对不起，元素加载异常，请联系管理员！")  }/>
        );
    }
}
Login = WeaTools.tryCatch(React, MyErrorHandler, { error: "" })(Login);
export default Login;


